<template>
  <el-drawer v-model="show" size="820px" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
    <template #header>
      <div class="drawer-header">
        <span class="drawer-title">新增支付宝代扣商家</span>
        <el-icon @click="closeDialog" color="#909399" size="16" style="cursor: pointer">
          <Close />
        </el-icon>
      </div>
    </template>
    <div class="pane">
      <el-form ref="formRef" :model="form" :rules="formRules" :label-width="150">
        <div class="title">
          <div class="text">基本信息</div>
        </div>
        <el-row :gutter="10">
          <!-- <el-col :span="12">
            <el-form-item prop="agent_partner_id" label="区域渠道">
              <el-select v-model="form.agent_partner_id" :disabled="partnerDisabled">
                <el-option v-for="(item, index) in partnerList" :label="item.real_name" :value="item.id"
                  :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="agent_partner_rate" label="渠道分成费率">
              <el-input v-model="form.agent_partner_rate" :disabled="true" placeholder="请输入渠道分成费率" :min="0" :max="9.99" type="number">
                <template #append>%</template>
              </el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item prop="agent_service_id" label="服务商">
              <el-select v-model="form.agent_service_id" :disabled="true">
                <el-option v-for="(item, index) in serviceList" :label="item.real_name" :value="item.id"
                  :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="agent_service_rate" label="服务商分成费率">
              <el-input v-model="form.agent_service_rate" :disabled="true" placeholder="请输入渠道分成费率" :min="0" :max="9.99" type="number">
                <template #append>%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="company_name" label="营业执照公司全称">
              <el-input v-model="form.company_name" placeholder="请输入营业执照公司全称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="license_no" label="营业执照编码">
              <el-input v-model="form.license_no" placeholder="请输入营业执照编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="short_name" label="商户简称">
              <el-input v-model="form.short_name" placeholder="请输入商户简称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="bank_card_no" label="支付宝账号">
              <el-input v-model="form.bank_card_no" placeholder="请输入支付宝账号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="legal_person_name" label="法人姓名">
              <el-input v-model="form.legal_person_name" placeholder="请输入法人姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="legal_person_mobile" label="法人手机号">
              <el-input v-model="form.legal_person_mobile" placeholder="请输入法人手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="connect_name" label="联系人">
              <el-input v-model="form.connect_name" placeholder="请输入联系人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="connect_mobile" label="联系电话">
              <el-input v-model="form.connect_mobile" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="area_id" label="所在地区">
              <div style="display: flex; height: 100%; width: 100%">
                <div style="flex: 1; height: 100%">
                  <el-select v-model="form.province_id" style="width: 100%" @change="provinceChange" clearable>
                    <el-option v-for="(item, index) in province_list" :label="item.region_name" :value="item.id"
                      :key="index"></el-option>
                  </el-select>
                </div>
                <div style="flex: 1; height: 100%; margin: 0 10px">
                  <el-select v-model="form.city_id" style="width: 100%" @change="cityChange" clearable>
                    <el-option v-for="(item, index) in city_list" :label="item.region_name" :value="item.id"
                      :key="index"></el-option>
                  </el-select>
                </div>
                <div style="flex: 1; height: 100%">
                  <el-select v-model="form.area_id" style="width: 100%" @change="areaChange" clearable>
                    <el-option v-for="(item, index) in area_list" :label="item.region_name" :value="item.id"
                      :key="index"></el-option>
                  </el-select>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="address" label="详细地址">
              <el-input v-model="form.address" placeholder="请输入详细地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="service_mobile" label="客服电话">
              <el-input v-model="form.service_mobile" placeholder="请输入客服电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">
          <div class="text">证件照片</div>
        </div>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="营业执照" prop="license_image">
              <el-upload v-model:file-list="license_image_list" :action="baseUrl + 'v1/tools/file/upload'"
                list-type="picture-card" accept=".png,.gif,.jpeg,.jpg" :headers="{
                  'x-token': token,
                }" :data="{
  module: 'seller_file',
}" :limit="1" :with-credentials="true" :on-remove="(res) => {
  handleImgRemove(res, 'license_image')
}" :on-success="(res) => {
  handleImgSuccess(res, 'license_image');
}">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>

            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="lega_card_front" label="法人身份证正面照片">
              <el-upload v-model:file-list="lega_card_front_list" :action="baseUrl + 'v1/tools/file/upload'"
                list-type="picture-card" accept=".png,.gif,.jpeg,.jpg" :headers="{
                  'x-token': token,
                }" :data="{
  module: 'seller_file',
}" :limit="1" :with-credentials="true" :on-remove="(res) => {
  handleImgRemove(res, 'lega_card_front')
}" :on-success="(res) => {
    handleImgSuccess(res, 'lega_card_front');
  }
  ">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="lega_card_back" label="法人身份证反面照片">
              <el-upload v-model:file-list="lega_card_back_list" :action="baseUrl + 'v1/tools/file/upload'"
                list-type="picture-card" accept=".png,.gif,.jpeg,.jpg" :headers="{
                  'x-token': token,
                }" :data="{
  module: 'seller_file',
}" :limit="1" :with-credentials="true" :on-remove="(res) => {
  handleImgRemove(res, 'lega_card_back')
}" :on-success="(res) => {
    handleImgSuccess(res, 'lega_card_back');
  }
  ">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">
          <div class="text">门店照片</div>
        </div>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item prop="door_head_image" label="门头照片">
              <el-upload v-model:file-list="door_head_image_list" :action="baseUrl + 'v1/tools/file/upload'"
                list-type="picture-card" accept=".png,.gif,.jpeg,.jpg" :headers="{
                  'x-token': token,
                }" :data="{
  module: 'seller_file',
}" :limit="1" :with-credentials="true" :on-remove="(res) => {
  handleImgRemove(res, 'door_head_image')
}" :on-success="(res) => {
    handleImgSuccess(res, 'door_head_image');
  }
  ">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="foreground_image" label="前台照片">
              <el-upload v-model:file-list="foreground_image_list" :action="baseUrl + 'v1/tools/file/upload'"
                list-type="picture-card" accept=".png,.gif,.jpeg,.jpg" :headers="{
                  'x-token': token,
                }" :data="{
  module: 'seller_file',
}" :limit="1" :with-credentials="true" :on-remove="(res) => {
  handleImgRemove(res, 'foreground_image')
}" :on-success="(res) => {
    handleImgSuccess(res, 'foreground_image');
  }
  ">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="storefront_images" label="店内照片">
              <el-upload v-model:file-list="storefront_images_list" :action="baseUrl + 'v1/tools/file/upload'"
                list-type="picture-card" accept=".png,.gif,.jpeg,.jpg" :headers="{
                  'x-token': token,
                }" :data="{
  module: 'seller_file',
}" :limit="3" :with-credentials="true" :on-remove="(res) => {
  handleImgRemove(res, 'storefront_images')
}" :on-success="(res) => {
    handleImgSuccess(res, 'storefront_images');
  }
  ">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title" style="justify-content: flex-start">
          <div class="text">协议文件</div>
          <div class="desc">(支持Word/pdf/excel等格式)</div>
        </div>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item prop="contract_file" label="合同文件">
              <el-upload v-model:file-list="contract_file_list" :action="baseUrl + 'v1/tools/file/upload'"
                accept=".xls,.xlsx,.doc,.docx,.pdf,.png,.gif,.jpeg,.jpg" list-type="text" :headers="{
                  'x-token': token,
                }" :data="{
  module: 'seller_file',
}" :limit="1" :with-credentials="true" :on-remove="(res) => {
  handleImgRemove(res, 'contract_file')
}" :on-success="(res) => {
    handleImgSuccess(res, 'contract_file');
  }
  ">
                <el-button type="primary">上传文件</el-button>

              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      
      <div v-if="state == 'add' || state == 'edit'">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="save(formRef)">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";

import cookies from "libs/cookies";
import { ElMessageBox, ElMessage } from 'element-plus'

import { Plus, Close } from "@element-plus/icons-vue";

import { getAgentPartnerList, getAgentServiceList } from "services/common";

import { getRegion } from "services/system";

import { setAlipayShop, getAlipayDetail } from "services/shop"

import systemStore from "@/store/modules/system";

const props = defineProps<{
  drawerShow: boolean,
  id?: string,
  state: string

}>();

const emit = defineEmits(['close', 'refresh'])

const baseUrl = import.meta.env.GZG_BASE_URL;

const token = cookies.get("token");

const formRef = ref<FormInstance>();

const formRules = reactive<FormRules>({
  company_name:[{required:true,message:'请输入营业执照公司全称'}],
  short_name:[{required:true,message:'请输入商户简称'}],
  license_no:[{required:true,message:'请输入营业执照编码'}],
  bank_card_no:[{required:true,message:'请输入支付宝账号'}],
  connect_name:[{required:true,message:'请输入联系人'}],
  connect_mobile:[{required:true,message:'请输入联系电话'}],
  area_id:[{required:true,message:'请选择所在地区',trigger:'change'}],
  address:[{required:true,message:'请输入详细地址'}],
  license_image:[{required:true,message:'请上传营业执照', trigger:'change'}],
  lega_card_front:[{required:true,message:'请上传法人身份证正面照片', trigger:'change'}],
  lega_card_back:[{required:true,message:'请上传法人身份证反面照片', trigger:'change'}],
  door_head_image:[{required:true,message:'请上传门头照片', trigger:'change'}],
  foreground_image:[{required:true,message:'请上传前台照片', trigger:'change'}],
  storefront_images:[{required:true,message:'请上传店内照片', trigger:'change'}],
});

const show = ref(false)

const partnerDisabled = ref(true)

const partnerList = ref<any>([]);
const serviceList = ref<any>([]);

const province_list = ref<any>([]);
const city_list = ref<any>([]);
const area_list = ref<any>([]);

const license_image_list = ref<any>([]);
const lega_card_front_list = ref<any>([]);
const lega_card_back_list = ref<any>([]);
const door_head_image_list = ref<any>([]);
const foreground_image_list = ref<any>([]);
const storefront_images_list = ref<any>([]);
const contract_file_list = ref<any>([]);

const form = reactive({
  id: '', //编辑id
  company_name: "", //公司名称
  license_no: "", //营业执照编号
  short_name: "", //商户简称
  legal_person_name: "", //法人姓名
  legal_person_mobile: "", //法人手机号
  bank_account: "", //支付宝姓名
  bank_card_no: "", //支付宝账号
  connect_name: "", //联系人
  connect_mobile: "", //联系人手机号
  province_id: "", // 省id
  city_id: "", // 市id
  area_id: "", //区域id
  address: "", //详细地址
  service_mobile: "", //客服电话
  agent_partner_id: "", //渠道商id
  agent_partner_rate: "", //渠道分成费率
  agent_service_id: "", //服务商id
  agent_service_rate: "", //服务商分成费率
  license_image: "", //营业执照图
  lega_card_front: "", //法人身份证正面图
  lega_card_back: "", //法人身份证反面图
  door_head_image: "", //门头照片
  foreground_image: "", //前台照片
  storefront_images: <any>[], //店内照片组
  contract_file: {
    url: '',
    name: ''
  }, //合同文件
});

const initData = () => {
  getRegion({ parent_id: 0 }).then((res) => {
    province_list.value = res.items;
  });

  // getAgentPartnerList({}).then(res => {
  //   partnerList.value = res.items
  // })

  getAgentServiceList().then((res) => {
    res.items.forEach((item:any) => {
        item.real_name = desensitize(item.real_name)
    })
    serviceList.value = res.items;
  });
};

const handleImgSuccess = (data: any, type: any) => {
  if (data.code == 0) {
    if (type == 'storefront_images') {
      form['storefront_images'].push(data.data.file[0].absolute_path);

    } else if (type == 'contract_file') {
      form['contract_file'] = {
        name: data.data.file[0].name,
        url: data.data.file[0].absolute_path
      }
    } else {
      form[type] = data.data.file[0].absolute_path;

    }
  }
};

const handleImgRemove = (file: any, type: any) => {
  console.log(file, type)
  if (type == 'storefront_images') {
    let i = 0
    form['storefront_images'].forEach((url: any, index: number) => {
      if (url == file.url) {
        i = index
      }
    })

    form['storefront_images'].splice(i, 1)
  } else if (type == 'contract_file') {
    form['contract_file'] = {
      name: '',
      url: ''
    }
  } else {
    form[type] = ''
  }
}

const provinceChange = (val: any) => {
  console.log(val);
  if (val) {
    getRegion({ parent_id: val }).then((res) => {
      city_list.value = res.items;
    });
  }
};

const cityChange = (val: any) => {
  console.log(val);
  if (val) {
    getRegion({ parent_id: val }).then((res) => {
      area_list.value = res.items;
    });
  }
};

const areaChange = (val: any) => {
  if (val) {
    if (userInfo.value.agent_type == "2") {
      getAgentPartnerList({ area_id: val }).then((res) => {
        if (res.items.length > 0) {
          res.items.forEach((item:any) => {
            item.real_name = desensitize(item.real_name)
          })
        }
        partnerList.value = res.items;
        if (res.items.length == 1 ) {
          form.agent_partner_id = res.items[0].id
        }

        if (res.items.length > 1) {
          partnerDisabled.value = false
        }
      });
    }
  }
};

const closeDialog = () => {
  emit('close')
}

const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      setAlipayShop(form).then(res => {
        ElMessage.success('申请成功')
        emit('refresh')
      })
    }
  })
}

const desensitize = (val:string) => {
  if (val.length == 1) {
    return val
  } else if (val.length == 2) {
    return `*${val.substring(val.length - 1)}`
  } else if (val.length > 2) {
    return `**${val.substring(val.length - 1)}`

  }

  return val
}


const getDetail = (val: any) => {
  getAlipayDetail({
    id: val
  }).then(res => {
    console.log(res)
    getRegion({ parent_id: res.province_id }).then((res) => {
      city_list.value = res.items;
    });

    getRegion({ parent_id: res.city_id }).then((res) => {
      area_list.value = res.items;
    });

    getAgentPartnerList({ area_id: res.area_id }).then((res) => {
      res.items.forEach((item:any) => {
        item.real_name = desensitize(item.real_name)
      })
      partnerList.value = res.items;
    });

    getAgentServiceList().then((res) => {
      res.items.forEach((item:any) => {
        item.real_name = desensitize(item.real_name)
      })
      serviceList.value = res.items;
    });
    form.id = res.id //编辑id
    form.company_name = res.company_name //公司名称
    form.license_no = res.license_no //营业执照编号
    form.short_name = res.short_name //商户简称
    form.legal_person_name = res.legal_person_name //法人姓名
    form.legal_person_mobile = res.legal_person_mobile //法人手机号
    form.bank_account = res.bank_account //支付宝姓名
    form.bank_card_no = res.bank_card_no //支付宝账号
    form.connect_name = res.connect_name //联系人
    form.connect_mobile = res.connect_mobile //联系人手机号
    form.province_id = res.province_id // 省id
    form.city_id = res.city_id // 市id
    form.area_id = res.area_id //区域id
    form.address = res.address //详细地址
    form.service_mobile = res.service_mobile //客服电话
    form.agent_partner_id = res.agent_partner_id //渠道商id
    form.agent_partner_rate = res.agent_partner_rate //渠道分成费率
    form.agent_service_id = res.agent_service_id //服务商id
    form.agent_service_rate = res.agent_service_rate, //服务商分成费率
      form.license_image = res.license_image, //营业执照图
      form.lega_card_front = res.lega_card_front, //法人身份证正面图
      form.lega_card_back = res.lega_card_back //法人身份证反面图
    form.door_head_image = res.door_head_image //门头照片
    form.foreground_image = res.foreground_image //前台照片
    form.storefront_images = res.storefront_images //店内照片组
    form.contract_file = res.contract_file //合同文件

    license_image_list.value = [{ url: res.license_image }]
    lega_card_front_list.value = [{ url: res.lega_card_front }]
    lega_card_back_list.value = [{ url: res.lega_card_back }]
    door_head_image_list.value = [{ url: res.door_head_image }]
    foreground_image_list.value = [{ url: res.foreground_image }]
    storefront_images_list.value = res.storefront_images.map((url: any) => {
      return { url: url }
    })
    contract_file_list.value = [{ url: res.contract_file.url, name: res.contract_file.name }]

  })
}

// const partnerDisabled = computed(() => {
//   let result = false;
//   if (userInfo.value.agent_type == "2") {
//     if (!form.area_id) {
//       result = true;
//     }
//   }
//   return result;
// });

const userInfo = computed(() => {
  return systemStore().userInfo;
});

const dict = computed(() => {
  return systemStore().dict
})


watch(() => props.drawerShow, (newVal: any) => {
  console.log(newVal)
  if (newVal == true) {
    if (props.state == 'add') {
        formRef.value?.resetFields()

        license_image_list.value = []
        lega_card_front_list.value = []
        lega_card_back_list.value = []
        door_head_image_list.value = []
        foreground_image_list.value = []
        storefront_images_list.value = []
        contract_file_list.value = []
    }
  }
  show.value = newVal
}, {
  immediate: true
})

watch(() => props.id, (newVal: any) => {
  console.log(newVal, 'new ')
  if (newVal) {
    getDetail(newVal)
  } else {
    form.id = '' //编辑id
    form.company_name = '' //公司名称
    form.license_no = '' //营业执照编号
    form.short_name = '' //商户简称
    form.legal_person_name = '' //法人姓名
    form.legal_person_mobile = '' //法人手机号
    form.bank_account = '' //支付宝姓名
    form.bank_card_no = '' //支付宝账号
    form.connect_name = '' //联系人
    form.connect_mobile = '' //联系人手机号
    form.province_id = '' // 省id
    form.city_id = '' // 市id
    form.area_id = '' //区域id
    form.address = '' //详细地址
    form.service_mobile = '' //客服电话
    form.agent_partner_id = '' //渠道商id
    form.agent_partner_rate = '' //渠道分成费率
    form.agent_service_id = '' //服务商id
    form.agent_service_rate = '' //服务商分成费率
    form.license_image = '', //营业执照图
      form.lega_card_front = '', //法人身份证正面图
      form.lega_card_back = '' //法人身份证反面图
    form.door_head_image = '' //门头照片
    form.foreground_image = '' //前台照片
    form.storefront_images = []//店内照片组
    form.contract_file = {
      url: '',
      name: ''
    } //合同文件

    license_image_list.value = []
    lega_card_front_list.value = []
    lega_card_back_list.value = []
    door_head_image_list.value = []
    foreground_image_list.value = []
    storefront_images_list.value = []
    contract_file_list.value = []

    if (dict.value.default_rate_data.open_status == 1) {
      if (userInfo.value.agent_type == '1') {
        form.agent_partner_id = userInfo.value.id
        form.agent_partner_rate = dict.value.default_rate_data.agent_rate
        partnerList.value = [{
          real_name:userInfo.value.real_name,
          id:userInfo.value.id
        }]
      } else if (userInfo.value.agent_type == '2') {
        form.agent_partner_rate = dict.value.default_rate_data.agent_rate
        form.agent_service_id = userInfo.value.id
        form.agent_service_rate = dict.value.default_rate_data.service_rate
      }
    } else {
      if (userInfo.value.agent_type == '1') {
        form.agent_partner_id = userInfo.value.id
        form.agent_partner_rate = '0'
        partnerList.value = [{
          real_name:userInfo.value.real_name,
          id:userInfo.value.id
        }]
      } else if (userInfo.value.agent_type == '2') {
        form.agent_partner_rate ='0'
        form.agent_service_id = userInfo.value.id
        form.agent_service_rate = '0'
      }
    }
  }
}, {
  immediate:true
})

onMounted(() => {
  initData();
});
</script>
